import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import 'other/permission_helper.dart';

class ChatAddView extends StatelessWidget {
  final Function photoHandle;

  ChatAddView({Key? key, required this.photoHandle}) : super(key: key);
  final List<Map> _titles = [
    {"拍照": "chat_camera"},
    {"相册": "chat_photo"},
  ];
  @override
  Widget build(BuildContext context) {
    double marginX = (MediaQuery.of(context).size.width - 80 * 4) / 5;
    double marginY = (300 - 100 * 2) / 3;

    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.green,
      child: GridView.builder(
          padding: EdgeInsets.fromLTRB(marginX, marginY, marginX, marginY),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4, //每行个数
              crossAxisSpacing: marginX, //左右
              mainAxisSpacing: marginY, //上下
              childAspectRatio: 0.8),
          itemCount: _titles.length,
          itemBuilder: (ctx, index) {
            return GestureDetector(
                //设置成不透明
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  ImageSource source =
                      index == 0 ? ImageSource.camera : ImageSource.gallery;
                  XFile? pickedFile = await PermissionHelper.showImagePicker(
                      context,
                      source: source);
                  if (pickedFile == null) {
                    return;
                  }
                  //bae64字符串
                  List<int> imageBytes = await pickedFile.readAsBytes();
                  String imageStr =
                      "data:image/png;base64," + base64Encode(imageBytes);
                  print(imageStr);
                  photoHandle(pickedFile.path);
                },
                child: Column(
                  children: [
                    const SizedBox(height: 10),
                    Container(
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10)),
                      child: Image.asset(
                        "lib/images/${_titles[index].values.toList()[0]}.png",
                        width: 50,
                        height: 50,
                        fit: BoxFit.cover,
                      ),
                    ),
                    const SizedBox(height: 10),
                    Text(_titles[index].keys.toList()[0]),
                  ],
                ));
          }),
    );
  }
}
